export const preZero = n => {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}
/*
  获取随机字符串
  @params:
  len: 字符串长度
  @return[String]：字符串
*/
export const generateMixed = (len=4) => {
  const chars=[
    '0','1','2','3','4','5','6','7','8','9',
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
  ]
  let res=''
  for(let i=0; i<len; i++){
    let index=Math.ceil(Math.random()*61)
    res+=chars[index]
  }
  return res
}

export const dateFormat = date => {
  date = new Date(date)
  const now = new Date()
  const dValue = date.getTime() - now.getTime()
  const suffix = dValue >= 0 ? '后' : '前'
  const MINUTE = 60 * 1000
  const HOUR = 60 * MINUTE
  const DAY = 24 * HOUR
  const MONTH = 30 * DAY
  const YEAR = 12 * MONTH
  const mapType = {
    [MINUTE]: '分钟',
    [HOUR]: '小时',
    [DAY]: '天',
    [MONTH]: '月',
    [YEAR]: '年',
  }
  const result = timeType => Math.floor(dValue/timeType) + mapType[timeType] + suffix
  switch(true){
    case dValue >= YEAR:
      return result(YEAR)
    case dValue >= MONTH:
      return result(MONTH)
    case dValue >= DAY:
      return result(DAY)
    case dValue >= HOUR:
      return result(HOUR)
    case dValue >= MINUTE:
      return result(MINUTE)
    default:
      return `${date.getFullYear()}/${date.getMonth()+1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
  }
}

export const storageAdd = (key, value_or_index, value) => {
  let data = localStorage.getItem(key)
  data = data ? JSON.parse(data) : (value ? {} : [])
  value ? data[value_or_index] = value : data.push(value_or_index)
  localStorage.setItem(key, JSON.stringify(data))
  return data
}

export const storageGet = key => {
  let data = localStorage.getItem(key)
  return data ? JSON.parse(data) : null
}

export const stopTimeFormat = timeStamp => {
  // 带时分秒的截止时间
  const stopDate = new Date(timeStamp)
  const stopH = preZero(stopDate.getHours())
  const stopM = preZero(stopDate.getMinutes())
  // 除去时分秒的截止时间和现在时间
  const date = new Date(new Date(timeStamp).setHours(0, 0, 0, 0))
  const now = new Date(new Date().setHours(0, 0, 0, 0))
  const result = ctx => ctx + '前完成'
  const sMonth = date.getMonth() + 1
  const sDate = date.getDate()
  const nowMonth = now.getMonth() + 1
  const nowDate = now.getDate()
  const nowTimestamp = now.getTime()
  const mapDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  if (nowMonth === sMonth && nowDate === sDate) {
    return result(`今天${stopH}:${stopM}`)
  } else if (date.getTime() - nowTimestamp === 3600 * 24 * 1000) {
    return result(`明天${stopH}:${stopM}`)
  } else {
    return result(`${sMonth}·${sDate}(${mapDay[date.getDay()]}) ${stopH}:${stopM}`)
  }
}

export default {
  preZero,
  generateMixed,
  dateFormat,
  storageAdd,
  storageGet,
  stopTimeFormat
}